package com.dq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.mychain.gov.sdk.GovDataSDK;
import com.alipay.mychain.gov.sdk.base.*;
import com.alipay.mychain.gov.sdk.facade.enums.EncryptTpyeEnum;
import com.alipay.mychain.gov.sdk.request.SignedRequest;
import com.nuonuo.plate.extracte.BaseExtracte;
import org.apache.http.entity.ContentType;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo {
    //企业纳税⼈识别号
    private static String instCode = "123305214712205444";  //纳税人识别号
    //企业密码
    private static String password = "t8c5SZxNo9gdqyTR";  // 企业密码
    //企业密钥
    private static String privateKeyContent = "-----BEGIN ENCRYPTED PRIVATE KEY-----\n" +
            "MIH6MFUGCSqGSIb3DQEFDTBIMCcGCSqGSIb3DQEFDDAaBBQ1q5SSJCbGzH3x4ZwD\n" +
            "hbku7fReqwICCAAwHQYJYIZIAWUDBAEqBBA0tFuwuulSgYGksmT8AQusBIGg2YBC\n" +
            "lx4+N9MMTSZ/30klZ3deeNEMEIdgJS00/UbvT/aqjvqqnoV/ZLrNejbUqnOhjDTW\n" +
            "+InSw1P+Zp6k+K4cj+KMUtbNzTTTdZ3FBN1IEwCe52U7ibVbOmkoSemMH3rHPpIv\n" +
            "yCnIGbkQbg6xUWoc6alURXDaiQtRLixTuDF3inKDWNPFJOt6wo+LoYvqQa6cy28N\n" +
            "PfyCbXWqi1HUyXI/vw==\n" +
            "-----END ENCRYPTED PRIVATE KEY-----";


    public static void main(String[] args)  {

        // 获取总页数
        // 注意：每次获取总页数接口 requestId 都需要变换，  并且获取总页数和分页数据的requestId必须保持一致
        String requestId = "FFFFFFFFFFFFFF"+"_"+ System.currentTimeMillis();
        GenericResult count = packageCount(requestId,"2024-09-10", 2);



        // 获取分页数据,并解密。
        // 注意：获取分页数据的requestId都需要与获取总页数接口的requestId保持一致。
        GenericResult result=packageInfo(requestId, "1");




        // OFD文件解析
        // 获取分页数据和存放路径
        String fileDirPathSrc="/opt/hyht/ofd";   // 根据自身实际路径自行修改
        GenericResult decryptList= decryptList(result.getData(),fileDirPathSrc);
        // 获取刚刚下载好的文件地址解析成json数据
        GenericResult jsonList=getOfdToJson(fileDirPathSrc);
        System.out.println("执行成功");


    }



    /**
     * 获取总页数
     * @param jgrq 加工日期
     * @param requestId
     * @param gxfbs 购销方标识
     */
    public static GenericResult packageCount(String requestId,String jgrq,int gxfbs) {
        String jsonStr = JSONObject.toJSONString(new LinkedHashMap<String, Object>(5) {
            {
                put("authorizedNsrsbh", instCode);
                put("gxfbs", gxfbs);
                put("jgrq", jgrq);
                put("nsrsbh", instCode);
                put("requestId", requestId);
            }
        });
        String sign = sign(jsonStr);
        return   post(sign, "http://zlbp.zhejiang.chinatax.gov.cn/api/zww/invoice/file/getInvoiceFilePackageCount");

    }

    /**
     * 获取分页内容
     * @param pageNumber 分页数
     * @param requestId
     */
    public static GenericResult packageInfo(String requestId,String pageNumber) {
        String jsonStr = JSONObject.toJSONString(new LinkedHashMap<String, Object>(3) {
            {
                put("nsrsbh", instCode);
                put("requestId",requestId);
                put("pageNumber", pageNumber);
            }
        });
        String sign = sign(jsonStr);
        return post(sign, "http://zlbp.zhejiang.chinatax.gov.cn/api/zww/invoice/file/getInvoiceFilePackagesInfo");
    }

    private static String sign(String jsonStr) {
        GovDataSDK.getInstance().init(instCode, privateKeyContent, password, EncryptTpyeEnum.SM4);
        SignedRequest request = GovDataSDK.getInstance().getRequestBuilder().generateSignedPayload(jsonStr);
        return JSON.toJSONString(request);
    }

    private static GenericResult post(String jsonStr, String uri) {
        String response = null;
        try {
            response = HttpClientUtils.doPost(uri, jsonStr, ContentType.APPLICATION_JSON);
        } catch (Exception e) {
            e.printStackTrace();
        }

        BaseRestResult baseRestResult = JSON.parseObject(response, BaseRestResult.class);
        System.out.println("result:" + baseRestResult);

        GenericResult result = JSON.parseObject(response, GenericResult.class);
        System.out.println(result);
        return result;
    }

    // private static void dealFileResult(FileResultZww fileResult, Integer times)
    //         throws IOException {
    //     decrypt(fileResult, times);
    // }

    private static void decrypt(FileResultZww fileResult, Integer times, String instCode, String password, String privateKeyContent)
            throws IOException {
        DecryptAndVerifyUtils decryptAndVerifyUtils = new DecryptAndVerifyUtils(instCode, password, privateKeyContent);
        byte[] data = decryptAndVerifyUtils.decryptZww(fileResult);
        //解密到指定目录下
        String filePath = "hyht" + "/" + times + "/";
        // OssUtils.uploadFile(data,OssUtils.getOSSClient(),filePath);
    }

    //解析ofd文件下载到本地文件夹
    public static GenericResult decryptList(String dataList,String fileDirPathSrc) {
        List<FileResultZww> fileResultZwwList = JSON.parseArray(dataList, FileResultZww.class);
        GenericResult r= new GenericResult();
        List<String> filesPath=new ArrayList<>();
        System.out.println(filesPath.size());
        AtomicInteger total= new AtomicInteger(1);
        fileResultZwwList.forEach(frz -> {
            try {
                DecryptAndVerifyUtils decryptAndVerifyUtils = new DecryptAndVerifyUtils(instCode, password, privateKeyContent);
                byte[] data = decryptAndVerifyUtils.decryptZww(frz);
                String filePath = fileDirPathSrc + "/" + frz.getFileName();  //
                DataOutputStream out = new DataOutputStream(new FileOutputStream(filePath));
                byte[] b = data;
                for (int i = 0; i < b.length; i++) {
                    out.writeByte(b[i]);
                }
                out.flush();
                filesPath.add(filePath);
                total.getAndIncrement();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        r.setSuccess(true); r.setData(JSONObject.toJSONString(filesPath));r.setErrorCode("200");
        r.setErrorMsg("解密下载完成!共解密:"+fileResultZwwList.size()+"份,成功:"+filesPath.size()+"份.");
        return r;
    }


    // 解析ofd文件转为json格式数据
    public static GenericResult getOfdToJson(String fileDirPathSrc){
        GenericResult r=new GenericResult();
        try {
            List<JSONObject> jsonList=new ArrayList<>();
            File file = new File(fileDirPathSrc);
            File[] files = file.listFiles();
            File[] var4 = files;
            int var5 = files.length;
            for(int var6 = 0; var6 < var5; ++var6) {
                File f = var4[var6];
                if (!f.getName().endsWith(".xml")) {
                    InputStream is = new FileInputStream(f);
                    BaseExtracte baseExtracte = new BaseExtracte();
                    JSONObject jsonObject = baseExtracte.readXbrl(is);
                    jsonList.add(jsonObject);
                    is.close();
                }
            }
            r.setSuccess(true); r.setData(String.valueOf(jsonList));r.setErrorCode("200");
            r.setErrorMsg("解密完成!共解密:"+files.length+"份,成功:"+jsonList.size()+"份.");
            return r;
        }
        catch (IOException e) {
            r.setSuccess(false); r.setErrorCode("000001");
            r.setErrorMsg("操作失败");
            return r;
        }
    }
}

